package extra;

import psl.UserSession;
import psl.BasePage;
import psl.AppConstants;
import psl.CommonServices;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.util.*;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileOutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: phiteshkumar
 * Date: Feb 23, 2007
 * Time: 12:15:49 PM
 */
public class Controller extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest foRequest, HttpServletResponse foResponse)throws ServletException, IOException
    {
        System.out.println("In the Controller" );

        HashMap lhRequest = parseRequest(foRequest);

		HttpSession loHttpSession = foRequest.getSession(true);
		String lsSessionId = loHttpSession.getId();
		System.out.println("Session Id: " + lsSessionId);
		UserSession loUserSession = (UserSession)loHttpSession.getAttribute("UserSession");
		if (loUserSession == null)
		{
			loUserSession = new UserSession();
			loHttpSession.setAttribute("UserSession", loUserSession);
		}

		loUserSession.processRequest(lhRequest);
		BasePage loBasePage = loUserSession.getCurrentPage();
		String lsViewPage = loBasePage == null ? "Startup.html" : loBasePage.getViewPage();
		foRequest.getRequestDispatcher(lsViewPage).forward(foRequest, foResponse);

    }

    public HashMap parseRequest(HttpServletRequest foRequest)
    {
        HashMap lhRequest = new HashMap();
        Object[] loKeySet = foRequest.getParameterMap().keySet().toArray();
        for (int liCtr = 0; liCtr < loKeySet.length; liCtr++)
        {
            String lsKey = (String)loKeySet[liCtr];
            String lsValue = foRequest.getParameter(lsKey);
            if (lsValue != null && !lsValue.equals(""))
            {
                lhRequest.put(lsKey, lsValue);
            }
        }
        String lsAction = (String)lhRequest.get("action_fld");
        String[] laAction = CommonServices.stringToArray(lsAction, AppConstants.DELIM_MAIN + "");
        lhRequest.put("action_fld", laAction);
        return lhRequest;
    }

    static
    {
        try
        {
            PrintStream loPrintStream = new PrintStream(new FileOutputStream ("C:\\J2EEApplications\\Out\\Out.txt"));
            System.setOut(loPrintStream);
        }
        catch (Exception feException)
        {
        }
    }

}
